//const express = require("express");
//const app = express();
//const bodyParser = require("body-parser");

const http = require("http");
const url=require("url");
    

var Config=require("./Config.json");

const face=require('./face.js');

const fs=require('fs');

const crypto=require('crypto');
function md5(str){
    return crypto.createHash('md5').update(str).digest("hex");
}

/*
 * nginx 中要设置，去掉前缀路径
 * 访问https://xxx/face/getConfig 过来之后就是 /getConfig
    #baidu face auth
    location /face/ {
        proxy_pass http://127.0.0.1:6304/;
    }
*/

//curl -i -k 'https://device.hnsoc12349.cn/face/faceset/group/getlist' --data '{"appId":"26159037","data":{"group_id":"testgroup01"}}' -H 'Content-Type:application/json; charset=UTF-8'
//
function httpServer(req,res){

    req.setEncoding('utf-8');
    
    //console.log('req:',Object.keys(req));
    //console.log(req.method);
    //console.log(req.url);

    var data='';

    if(req.method=='GET'){
        query=url.parse(req.url,true);

        if(query.pathname=='/getConfig'){

            if(!query.query.appId || !Config[query.query.appId]){
                data={ error_code: -1, msg: 'FAIL', data:{error_msg:'请确认appId是否正确'}};
            }else{
                data={ error_code: 0, msg: 'SUCCESS', data:Config[query.query.appId]};
            }
        }else if(query.pathname=='/allConfig'){
            data={ error_code: 0, msg: 'SUCCESS', data:Config};
        }else if(query.pathname=='/delConfig'){
            if(!query.query.appId || !Config[query.query.appId]){
                data={ error_code: -1, msg: 'FAIL', data:{error_msg:'请确认appId是否正确'}};
            }else{
                delete Config[query.query.appId];

                  try {
                      fs.writeFileSync('./Config.json', JSON.stringify(Config));
                      data={'error_code':0,'msg':'SUCCESS',"data":{}};
                  } catch (e) {
                      console.log('写入配置文件发生错误', e);
                      data={error_code: -3, msg:'FAIL',data:{error_msg:'写入配置文件发生错误'}};
                  }
            }
        }else{
            data={'error_code':-2,'msg':'FAIL',"data":{'error_msg':'request url error'}};
        }

        res.setHeader( "Access-Control-Allow-Origin",
                req.headers && req.headers.origin ? req.headers.origin : "*"
                    );
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, x-mibu-token");

        res.setHeader("Content-Type","application/json;charset=utf8");
        res.writeHead(200);
        res.end(JSON.stringify(data));
        return;
    }else if(req.method=='OPTIONS'){

        res.setHeader( "Access-Control-Allow-Origin",
                req.headers && req.headers.origin ? req.headers.origin : "*"
                    );
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, x-mibu-token");

        res.setHeader("Content-Type","application/json;charset=utf8");
        res.writeHead(200);
        res.end();
        return;

    }



    //console.log('res:',Object.keys(res));
    //console.log('req.url=',req.url);

    var buf='';
    req.on('data',function(chunk){
        buf+=chunk;
    });
    req.on('end',async function(){

        if(buf.length==0){
            return;
        }

        var body='';
        try{
            body=JSON.parse(buf);
        }catch(e){
            console.log('Error','json parse error',buf.toString());
        }


        if(!body || !body.appId){
            data={'error_code':-1,'msg':'FAIL',"data":{'error_msg':'not post appId'}};
        }else if(req.url=='/setConfig'){
              Config[body.appId]=body.data;

              try {
                  fs.writeFileSync('./Config.json', JSON.stringify(Config));
                  data={'error_code':0,'msg':'SUCCESS',"data":{}};
              } catch (e) {
                  console.log('写入配置文件发生错误', e);
                  data={error_code: -3, msg:'FAIL',data:{error_msg:'写入配置文件发生错误'}};
              }
        }else if(!Config[body.appId]){
            data={'error_code':-1,'msg':'FAIL',"data":{'error_msg':'appId error'}};
        }else{

            if(!body.data){
                res.writeHead(404);
                res.end("need json data");
                return;
            }

            if(!body.data.group_id){
                body.data.group_id="mibu_health_cabin";
            }

            if(req.url=='/search'|| req.url=='/multi-search'){
                if(!body.data.group_id_list){
                    body.data.group_id_list="mibu_health_cabin";
                }
            }

            data=await face.common(Config[body.appId],req.url,body.data);
            if(data.error_code=='111'){
                delete Config[body.appId].access_token;
                data=await face.common(Config[body.appId],req.url,body.data);
            }

            if(req.url=='/faceset/user/add'){
                if(data.error_code==0){
                    data.data.user_id=body.data.user_id;
                    data.data.user_token=md5(body.data.group_id+"MBmb99"+body.data.user_id);
                }
            }else if(req.url=='/search'){

                if(data.error_code==0){
                    for(var i=0;i<data.data.result.user_list.length;i++){
                        var user=data.data.result.user_list[i];
                        user.user_token=md5(user.group_id+"MBmb99"+user.user_id);
                    }
                }
            }else if(req.url=='/multi-search'){
                if(data.error_code==0){
                    face_list=data.data.result.face_list;
                    for(var i=0;i<face_list.length;i++){
                        var user_list=face_list[i].user_list;
                        for(var j=0;j<user_list.length;j++){
                            var user=user_list[j];
                            user.user_token=md5(user.group_id+"MBmb99"+user.user_id);
                        }
                    }
                }
            }
        }


        //console.log(req.method,req.url);
        //console.log(JSON.stringify(body,"","\t"));

        res.setHeader( "Access-Control-Allow-Origin",
                req.headers && req.headers.origin ? req.headers.origin : "*"
                    );
        res.setHeader("Access-Control-Allow-Headers", "Content-Type, x-mibu-token");

        res.setHeader("Content-Type","application/json;charset=utf8");
        res.writeHead(200);
        res.end(JSON.stringify(data));
    });
}

server=http.createServer(httpServer);
server.listen(6304,function(){
    console.log("baidu face auth server listening on port %d", 6304);
});


/*
//获取配置
app.get("/", function (req, res) {
    data=req.query;
    res.json({"error_code":0,"msg":"test ok","data":data});
});

app.get("/getConfig", function (req, res) {

  const appId = req.query.appId;

  if (!appId || !Config[appId]) {
    res.json({ error_code: -1, msg: '请确认appId是否正确', data:{}});
  }else{
    res.json({ error_code: 0, msg: 'ok', data: Config[appId]});
  }
  return;
});

//单个配置
app.post("/setConfig", function (req, res) {

  var data='';
  req.on('data',function(chunk){
      data+=chunk;
  });
  req.on('end',function(){

    let body='';
    try {
      body=JSON.parse(data);
    }catch(e){
        res.json({ error_code: -1, msg: 'JOSN.parse() exception', data:data});
        return;
    }

      let appId=body.appId;

      Config[body.appId]=body;

        try {
          fs.writeFileSync('./Config.json', JSON.stringify(Config));
           res.json({ error_code: 0, msg: "ok", data: Config });

        } catch (e) {
          console.log('写入配置文件发生错误', e);
            res.json({ error_code: -2, msg: '写入配置文件发生错误', data: body });
        }

      body='';
  });

});

app.post("/groupadd", function (req, res) {
    var data='';
    req.on('data',function(chunk){
        data+=chunk;
    });
    req.on('end',async function(){
      var body='';
      try{
          body=JSON.parse(data);
          if(!body.appId || !body.group_id){
            res.json({ error_code: -2, msg: "缺少参数 appId、group_id",data:{} });
            return;
          }
      }catch(e){
          res.json({ error_code: -1, msg: "json parse except", data: data}); 
          return;
      }
      if(!Config[body.appId]){
        res.json({ error_code: -3, msg: "appId error",data:{} });
        return;
      }

      var r=await face.groupadd(Config[body.appId],body.group_id);

      res.json(r);
      data=''; 
    });
}

app.post("/search", function (req, res) {

    var data='';
    req.on('data',function(chunk){
        data+=chunk;
    });
    req.on('end',async function(){

      let body='';
      try{
          body=JSON.parse(data);
          if(!body.appId || !body.Phone || !body.TemplateCode || !body.TemplateParam){
            res.json({ error_code: -1, msg: "缺少参数", data: "appId、Phone、TemplateCode、TemplateParam" });
            return;
          }
      }catch(e){
          res.json({ error_code: -1, msg: "json parse except", data: data}); 
          return;
      }

      if(!Config[body.appId]){
          res.json({ error_code: -2, msg: "缺少" + body.appId + "的相关配置", data: "缺少" + body.appId + "的相关配置" });
          return;
      }

      console.log('/face/sendTemplate',Config[body.appId],body.Phone,body.TemplateCode,body.TemplateParam);

      console.log('param:',JSON.stringify(body.TemplateParam));

      r=await sms.SendSms(Config[body.appId],body.Phone,body.TemplateCode,body.TemplateParam);

      //r=await SendSms(config1,'18831344012','SMS_217870371',{"code":"112233"});
      //r={"error_code":0,"msg":"success"};

      res.json(r);

      data='';
    });
});



const server = http.createServer(app);
const port = process.env.PORT || 6304;
server.listen(port);
server.on("listening", function () {
  console.log("baidu face auth server listening on port %d", port);
});

process.on("exit", function () {
});
*/
